package org.jaaksi.kottlindemo

import java.util.SortedMap

/**
 * RxCacheKey 生成器，格式：url?key1=value1&key2=value2
 * 过滤掉空value及""
 */
class CacheKeyGenerator(private val url: String) {
  private var params: SortedMap<String, Any>? = null

  fun param(key: String, value: Any?): CacheKeyGenerator {
    if (value != null && value != "") {
      if (params == null) params = sortedMapOf()
      params!![key] = value
    }
    return this
  }

  fun create(): String {
    var url = this.url
    params?.let {
      url = url.plus("?")
      val iterator = params!!.iterator()

      while (iterator.hasNext()) {
        val entry = iterator.next()
        url = url.plus("${entry.key}=${entry.value}${if (iterator.hasNext()) "&" else ""}")
      }
    }

    return url

  }
}